package lumis.util;

import lumis.portal.PortalConfiguration;
import lumis.portal.PortalContext;
import lumis.portal.PortalException;
import lumis.portal.PortalStringResource;
import lumis.portal.controller.ControllerException;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.servlet.ServletUtil;
import lumis.portal.stability.StableMinor;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.id.UUIDHexGenerator;

/**
 * Utility methods for portal related functionalities.
 * 
 * @since 4.0.0
 * @version $Revision: 13082 $ $Date: 2011-05-27 16:03:12 -0300 (Fri, 27 May 2011) $
 */
@StableMinor(version = "6.0", sinceVersion = "4.0")
public abstract class PortalUtil
{
	private static final UUIDHexGenerator uuidGenerator = new UUIDHexGenerator();

	// -----------------------------------------------------------------------------

	public static String generateNewGuid()
	{
		return ((String)uuidGenerator.generate(null, null)).toUpperCase();
	}

	// -----------------------------------------------------------------------------

	public static String generateClientScript(String script)
	{
		return (script);
	}

	// -----------------------------------------------------------------------------
	/**
	 * Given a cookie name, the cookie value if exists in the request object is
	 * returned. If the cookie is not found, a null value is returned
	 * 
	 * @param name
	 * @return cookie value
	 * @deprected Since 4.0.7, use {@link CookieUtil#getCookie(HttpServletRequest, String)} instead.
	 */
	public static String getCookie(String name, HttpServletRequest request) throws ControllerException, PortalException
	{
		return CookieUtil.getCookie(request, name);
	}

	// -----------------------------------------------------------------------------

	public static String getExceptionDetailsHtml(Throwable e, HttpServletRequest request) throws Exception
	{
		String exceptionHtml = "<div class=\"cLumServiceInterfaceException\">";
		Throwable currentException = e;
		int count = 0;
		
		boolean displayButtonInserted = false;
		while(currentException != null)
		{
			String cookieMode = null;

			cookieMode = getCookie("lumMode", request);
			
			if(cookieMode != null && Integer.parseInt(cookieMode) == PortalContext.MODE_ADMIN)
			{
				if(count > 0)
				{
					exceptionHtml += "<br/>";
					exceptionHtml += "<div style=\"color:#656565;font-weight: bold;\"><b>CAUSADO POR:</b></div><br/>";
				}
				else
				{
					exceptionHtml += "<!--div style=\"color:#656565;font-weight: bold;\"><b>EXCEPTION</b></div><br/-->";
				}
			}
			
			exceptionHtml += "<div>";
			exceptionHtml += "<span style=\"color:#656565;font-weight: bold;font-size:11pt;\">"+XmlUtil.encodeXml(currentException.getLocalizedMessage())+"</span>";
			exceptionHtml += "<br/><br/>";
			
			if(PortalConfiguration.getCurrentConfiguration().isDevelopmentMode() ||
					(cookieMode != null && Integer.parseInt(cookieMode) == PortalContext.MODE_ADMIN))
			{
				if(!displayButtonInserted)
				{
					displayButtonInserted = true;
					exceptionHtml += "<form><input type=\"button\" id=\"display\" style=\"border:1px solid #c1c199;font-weight:bold;color:656565;background-color:#e0e0cc;\" onclick=\"toggleDisplay()\" value=\"" + ManagerFactory.getLocalizationManager().localize("STR_DETAILS", new PortalStringResource()) + "\" /></form>";
					exceptionHtml += "<script type=\"text/javascript\"> function toggleDisplay() { " +
							"var arrDivs = document.getElementsByTagName(\"div\"); " +
							"for(var i = 0; i < arrDivs.length; i++) " +
							"	if(arrDivs[i].className == \"divStack\")" +
							"		arrDivs[i].style.display = arrDivs[i].style.display == \"\" ? \"none\" : \"\"; } </script><noscript><!--Lumis portal script--></noscript>";  
				}
				
				exceptionHtml += "<div style=\"display:none\" class=\"divStack\">";
				exceptionHtml += "<i>Stack Trace:</i>";
				StringWriter sw = new StringWriter();
				PrintWriter pw = new PrintWriter(sw);
				currentException.printStackTrace(pw);
				exceptionHtml += "<textarea style='width:100%;height:300px'>"+XmlUtil.encodeXml(sw.toString())+"</textarea>";
				exceptionHtml += "</div>";
			}
			
			exceptionHtml += "</div>";

			if (currentException instanceof PortalException)
				currentException = ((PortalException)currentException).getCause();
			else
				currentException = null;
			
			count++;
		}		
		
		exceptionHtml += "</div>";
		
		return exceptionHtml;
	}
	
	/**
	 * Returns the website for the given request.
	 * <p>
	 * The website string is in the format '&lt;hostname&gt;:&lt;port&gt;/&lt;uri&gt;'.
	 * If the uri is empty, the slash will not be present.
	 * 
	 * @param request the request.
	 * @return the website string, or null if request is null.
	 * @since 4.0.6
	 */
	public static String getWebsite(HttpServletRequest request)
	{
		if (request != null)
		{
			String uri = getWebsiteUri(request);
			
			return request.getServerName() + ":" + request.getServerPort() + uri;
		}
		else
			return null;
	}
	
	/**
	 * Returns the website uri for the given request.
	 * <p>
	 * If the uri refers to the root directory, an empty string is returned.
	 * 
	 * @param request the request.
	 * @return the website uri string, or null if request is null.
	 * @since 4.0.6
	 */
	public static String getWebsiteUri(HttpServletRequest request)
	{
		if (request != null)
		{
			String uri = request.getRequestURI();
			String appPath = ServletUtil.getApplicationRequestedPath(request);
			
			// remove appPath substring from the uri
			int index = uri.lastIndexOf(appPath);
			if (index != -1)
				uri = uri.substring(0, index);
			
			// remove any ending '/' character
			if (uri.endsWith("/"))
				uri = uri.substring(0, uri.length()-1);
			
			return uri;
		}
		else
			return null;
	}

}
